<template>
  <div class="app-container">
    <vxe-grid ref="invitationCodeGridDom" v-bind="invitationCodeGridOpt" v-on="invitationCodeGridEvents">
      <template #toolbar-btns>
        <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onShowModal()">新增邀请码</vxe-button>
      </template>
      <template #row-operate="{ row }">
        <el-button link type="primary" @click="crudStore.onShowModal(row)">修改</el-button>
      </template>
    </vxe-grid>
    <vxe-modal ref="invitationCodeModalDom" v-bind="invitationCodeModalOpt">
      <!-- 表单 -->
      <vxe-form ref="invitationCodeFormDom" v-bind="invitationCodeFormOpt">
        <template #account-select>
          <el-select
            v-model="invitationCodeFormOpt.data.inviterId"
            placeholder="请选择数据"
            clearable
            filterable
            :filter-method="filterUser"
            :popper-append-to-body="true"
            popper-class="select-popper"
          >
            <el-option
              v-for="item in accountList"
              :key="item.id"
              :label="item.account"
              remote
              :value="item.id"
              placeholder="请输入"
            />
            <div style="bottom: -10px">
              <el-pagination
                small
                @current-change="handleCurrentChange"
                :current-page="currentpage"
                :page-size="pageSize"
                layout="prev, pager,next,total"
                :total="accountTotal"
              />
            </div>
          </el-select>
        </template>
      </vxe-form>
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, reactive, ref, onMounted } from "vue"
import { ElMessage } from "element-plus"
import {
  IInvitationCode,
  ICreateInvitationCodeDataApi,
  IGetInvitationCodeListDataApi,
  createInvitationCode,
  getInvitationCodeList,
  bindInviterAccount
} from "@/api/invitationCode"
import { IUserAccount, IGetMemberListDataApi, getMemberList } from "@/api/member"
import {
  type VxeGridInstance,
  type VxeGridProps,
  type VxeModalInstance,
  type VxeModalProps,
  type VxeFormInstance,
  type VxeFormProps,
  type VxeGridPropTypes,
  type VxeFormDefines,
  type VxeGridListeners
} from "vxe-table"

interface IRowMeta extends IInvitationCode {
  /** vxe-table 自动添加上去的属性 */
  createTime: string
  createUser: Number
  updateUser: Number
  updateTime: String
  _VXE_ID?: string
}

const currentpage = ref(1)

const pageSize = ref(10)

const accountTotal = ref(0)

const accountList = ref([])

const filterUser = (query = "") => {
  currentpage.value = 1
  searchUser(query)
}

const searchUser = (query = "") => {
  // const pageNum = currentpage.value + 1
  const params: IGetMemberListDataApi = { account: query, pageNum: currentpage.value, pageSize: pageSize.value }
  getMemberList(params).then((res) => {
    if (res && res.data) {
      accountList.value = res.data.list
      // currentpage.value = pageNum
      accountTotal.value = res.data.total
    }
  })
}

const handleCurrentChange = (page: number) => {
  currentpage.value = page
  searchUser("")
}

onMounted(() => {
  filterUser()
})

const invitationCodeGridDom = ref<VxeGridInstance>()

const invitationCodeGridOpt: VxeGridProps = reactive({
  loading: true,
  autoResize: true,
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: [
      {
        field: "typeNmae",
        itemRender: {
          name: "$input",
          props: { placeholder: "类型名", clearable: true }
        }
      },
      {
        itemRender: {
          name: "$buttons",
          children: [
            {
              props: { type: "submit", content: "查询", status: "primary" }
            },
            {
              props: { type: "reset", content: "重置" }
            }
          ]
        }
      }
    ]
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: true,
    slots: { buttons: "toolbar-btns" }
  },
  /** 自定义列配置项 */
  customConfig: {
    /** 是否允许列选中  */
    checkMethod: ({ column }) => !["typeName"].includes(column.field)
  },
  /** 列配置 */
  columns: [
    {
      type: "checkbox",
      width: "50px"
    },
    {
      field: "invitationCode",
      title: "邀请码"
    },
    {
      field: "inviterAccount",
      title: "绑定账号"
    },
    // {
    //   field: "enable",
    //   title: "是否启用",
    //   slots: EnableColumnSolts
    // },
    {
      field: "createTime",
      title: "创建时间"
    },
    {
      field: "createUser",
      title: "创建人"
    },
    {
      title: "操作",
      width: "150px",
      fixed: "right",
      showOverflow: false,
      slots: { default: "row-operate" }
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    // autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({ page, form }: VxeGridPropTypes.ProxyAjaxQueryParams) => {
        invitationCodeGridOpt.loading = true
        crudStore.clearTable()
        return new Promise<any>((resolve: Function) => {
          let total = 0
          let result: IRowMeta[] = []
          /** 加载数据 */
          const callback = (res: any) => {
            if (res && res.data) {
              const resData = res.data
              // 总数
              if (Number.isInteger(resData.total)) {
                total = resData.total
              }
              // 分页数据
              if (Array.isArray(resData.list)) {
                result = resData.list
              }
            }
            invitationCodeGridOpt.loading = false
            resolve({ total, result })
          }

          /** 接口需要的参数 */
          const params = {
            pageSize: page.pageSize,
            pageNum: page.currentPage
          }
          /** 调用接口 */
          getInvitationCodeList(params).then(callback).catch(callback)
        })
      }
    }
  }
})
//#endregion
//#region vxe-modal
const invitationCodeModalDom = ref<VxeModalInstance>()
const invitationCodeModalOpt: VxeModalProps = reactive({
  title: "",
  showClose: true,
  escClosable: true,
  maskClosable: true,
  zIndex: 2009,
  beforeHideMethod: () => {
    invitationCodeFormDom.value?.clearValidate()
    return Promise.resolve()
  }
})
//#endregion

const invitationCodeGridEvents: VxeGridListeners = {
  // cellClick({ row, column }) {
  //   if ("enable" === column.field) {
  //     crudStore.onSwitchRoleEnable(row)
  //   }
  // }
}

//#region vxe-form
const invitationCodeFormDom = ref<VxeFormInstance>()
const invitationCodeFormOpt = reactive<VxeFormProps>({
  span: 24,
  titleWidth: "100px",
  loading: false,
  /** 是否显示标题冒号 */
  titleColon: false,
  /** 表单数据 */
  data: {
    id: null,
    invitationCode: "",
    inviterId: null,
    inviterAccount: ""
  },
  /** 项列表 */
  items: [
    {
      field: "invitationCode",
      title: "邀请码",
      itemRender: { name: "$input", props: { placeholder: "请输入" } }
    },
    // {
    //   field: "inviterId",
    //   title: "绑定账户ID",
    //   itemRender: { name: "$input", props: { placeholder: "请输入" } }
    // },
    {
      field: "inviterId",
      title: "绑定账户",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "选择账号",
          clearable: true,
          options: accountList,
          optionProps: { value: "id", label: "account" }
        }
      },
      slots: { default: "account-select" }
    },
    {
      align: "right",
      itemRender: {
        name: "$buttons",
        children: [
          { props: { content: "取消" }, events: { click: () => invitationCodeModalDom.value?.close() } },
          {
            props: { type: "submit", content: "确定", status: "primary" },
            events: { click: () => crudStore.onSubmitForm() }
          }
        ]
      }
    }
  ],
  /** 校验规则 */
  rules: {
    invitationCode: [
      {
        required: true,
        validator: ({ itemValue }) => {
          if (!itemValue) {
            return new Error("请输入")
          }
          if (!itemValue.trim()) {
            return new Error("空格无效")
          }
        }
      }
    ]
  }
})
//#endregion

const crudStore = reactive({
  /** 表单类型：修改：true 新增：false */
  isUpdate: true,
  /** 加载表格数据 */
  commitQuery: () => invitationCodeGridDom.value?.commitProxy("query"),
  /** 清空表格数据 */
  clearTable: () => invitationCodeGridDom.value?.reloadData([]),
  /** 点击显示弹窗 */
  onShowModal: (row?: IRowMeta) => {
    if (row) {
      crudStore.isUpdate = true
      invitationCodeModalOpt.title = "修改邀请码"
      // 赋值
      invitationCodeFormOpt.data.id = row.id
      invitationCodeFormOpt.data.invitationCode = row.invitationCode
    } else {
      crudStore.isUpdate = false
      invitationCodeModalOpt.title = "新增邀请码"
    }
    // 禁用表单项
    if (invitationCodeFormOpt.items) {
      if (invitationCodeFormOpt.items[0]?.itemRender?.props) {
        invitationCodeFormOpt.items[0].itemRender.props.disabled = crudStore.isUpdate
      }
    }
    invitationCodeModalDom.value?.open()
    nextTick(() => {
      !crudStore.isUpdate && invitationCodeFormDom.value?.reset()
      invitationCodeFormDom.value?.clearValidate()
    })
  },
  /** 确定并保存 */
  onSubmitForm: () => {
    if (invitationCodeFormOpt.loading) return
    invitationCodeFormDom.value?.validate((errMap?: VxeFormDefines.ValidateErrorMapParams) => {
      if (errMap) return
      invitationCodeFormOpt.loading = true
      const callback = (err?: any) => {
        invitationCodeFormOpt.loading = false
        if (err) return
        invitationCodeModalDom.value?.close()
        ElMessage.success("操作成功")
        !crudStore.isUpdate && crudStore.afterInsert()
        crudStore.commitQuery()
      }
      if (crudStore.isUpdate) {
        // 调用修改接口
        const bindInviterAccountData = {
          inviterId: invitationCodeFormOpt.data.inviterId,
          inviterAccount: invitationCodeFormOpt.data.inviterAccount
        }
        bindInviterAccount(invitationCodeFormOpt.data.id, bindInviterAccountData)
          .then(() => {
            callback()
          })
          .catch((error) => callback(error))
      } else {
        // 调用新增接口
        createInvitationCode(invitationCodeFormOpt.data)
          .then(() => {
            callback()
          })
          .catch((error) => callback(error))
      }
    })
  },
  /** 新增后是否跳入最后一页 */
  afterInsert: () => {
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams = invitationCodeGridDom.value?.getProxyInfo()?.pager
    if (pager) {
      const currTotal: number = pager.currentPage * pager.pageSize
      if (currTotal === pager.total) {
        ++pager.currentPage
      }
    }
  },
  /** 删除 */
  // onDelete: (row: IRowMeta) => {
  //   const tip = `确定 <strong style='color:red;'>删除</strong> 邀请码 <strong style='color:#409eff;'>${row.typeName}</strong> ？`
  //   const config: ElMessageBoxOptions = {
  //     type: "warning",
  //     showClose: true,
  //     closeOnClickModal: true,
  //     closeOnPressEscape: true,
  //     cancelButtonText: "取消",
  //     confirmButtonText: "确定",
  //     dangerouslyUseHTMLString: true
  //   }
  //   ElMessageBox.confirm(tip, "提示", config)
  //     .then(() => {
  //       deleteRoleApi(row.id)
  //         .then(() => {
  //           ElMessage.success("删除成功")
  //           crudStore.afterDelete()
  //           crudStore.commitQuery()
  //         })
  //         .catch(() => 1)
  //     })
  //     .catch(() => 1)
  // },
  /** 删除后是否返回上一页 */
  afterDelete: () => {
    const tableData: IRowMeta[] = invitationCodeGridDom.value!.getData()
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams = invitationCodeGridDom.value?.getProxyInfo()?.pager
    if (pager && pager.currentPage > 1 && tableData.length === 1) {
      --pager.currentPage
    }
  },
  /** 更多自定义方法 */
  moreFunc: () => {}
})
</script>

<style scoped>
.select-popper {
  z-index: 50000 !important;
}
</style>
